package com.ruoyi.api.kehu;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RSADecrypt;
import com.ruoyi.common.utils.SmsTemplete;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.JiajiaHuoDong;
import com.ruoyi.system.domain.JiajiaMessage;
import com.ruoyi.system.domain.JiajiaProxyApplication;
import com.ruoyi.system.domain.JiajiaUser;
import com.ruoyi.system.domain.vo.WxUserInfoVo;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.SendSms;
import com.ruoyi.system.utils.TokenUtil;
import com.ruoyi.system.utils.WxUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/kehu/user")
@Api(tags = "用户管理")
public class ApiUserController {

    @Autowired
    private IJiajiaUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IJiajiaHuoDongService huoDongService;

    @Autowired
    private IJiajiaMessageService messageService;

    @Autowired
    private WxUtils wxUtils;

    @Autowired
    private  ApiPayService apiPayService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IJiajiaMappointsService jiajiaMappointsService;

    @Resource
    private IJiajiaProxyApplicationService proxyApplicationService;


    private static final Logger log = LoggerFactory.getLogger(ApiUserController.class);

    @ApiOperation("登陆")
    @PostMapping("/login")
    public AjaxResult login(@RequestParam String phone,
                            @RequestParam String code)
    {
        if(StringUtils.isEmpty(phone)){
            return AjaxResult.error("手机号不能为空");
        }
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("验证码不能为空");
        }


            String realCode =  redisTemplate.opsForValue().get(TokenUtil.jiajia_user_phone_login_code +phone);
            if (StringUtils.isEmpty(realCode)){
                return AjaxResult.error("请先获取验证码");
            }
            if (!realCode.equals(code)){
                return AjaxResult.error("验证码不对");
            }


        JiajiaUser user = new JiajiaUser();
        user.setPhone(phone);
        List<JiajiaUser> userList =  userService.selectJiajiaUserList(user);
        if (userList.isEmpty()){
            user.setName(StringUtils.isEmpty(phone)?"百吉星社工用户":phone);
            userService.insertJiajiaUser(user);
        }else {
            user = userList.get(0);
        }

        if (user.getDel().intValue() == 1)return AjaxResult.error("此账户已注销!");

        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(TokenUtil.jiajia_reids_token+uuid,user.getId()+"",60, TimeUnit.DAYS);
        return AjaxResult.success(uuid);
    }


    @ApiOperation("授权手机号")
    @PostMapping("/bindWxmallPhone")
    public AjaxResult bindWxmallPhone(@RequestParam String data,@RequestParam String iv, @RequestParam String jsCode,@RequestParam(required = false) String phone,@RequestParam(required = false) String inviter) {
        log.info("推荐人电话phone："+phone+"推荐人电话inviter："+inviter);
        WxUserInfoVo wxUserInfoVo = wxUtils.WxGetUserInfo(data, iv,jsCode);

        if (wxUserInfoVo == null){
            return AjaxResult.error("操作失败");
        }
        if (StringUtils.isEmpty(wxUserInfoVo.getPhoneNumber())){
            return AjaxResult.error("没有解析到手机号");
        }
        JiajiaUser user = new JiajiaUser();
        user.setPhone(wxUserInfoVo.getPhoneNumber());

        JiajiaUser jsonUser = userService.selectjiajiaUser(wxUserInfoVo.getPhoneNumber());

        if (ObjectUtil.isNull(jsonUser)){
            //推荐人
            if (StringUtils.isNotEmpty(phone)){
                user.setInviter(phone);
            }
            user.setName(StringUtils.isEmpty(user.getPhone())?"百吉星社工用户":user.getPhone());
            user.setOpenId(wxUserInfoVo.getOpenid());
            user.setUnionid(wxUserInfoVo.getUnionid());
            userService.insertJiajiaUser(user);
        }else {
            if (ObjectUtil.isNull(jsonUser.getOpenId())){
                jsonUser.setOpenId(wxUserInfoVo.getOpenid());
                userService.updateJiajiaUser(jsonUser);
            }
            if (ObjectUtil.isNull(jsonUser.getInviter())){
                jsonUser.setInviter(phone);
                userService.updateJiajiaUser(jsonUser);
            }
            user = jsonUser;
        }

        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(TokenUtil.jiajia_reids_token+uuid,user.getId()+"",60, TimeUnit.DAYS);
        return AjaxResult.success(uuid);
    }


    @ApiOperation("授权手机号")
    @PostMapping("/h5Login")
    public AjaxResult h5Login() {


        return null;
    }


    public static void main(String[] args) {
        System.out.println(StringUtils.isEmpty(""));
    }


    @ApiOperation("根据极光认证来登陆")
    @PostMapping("/loginByJiGuang")
    public AjaxResult loginByJiGuang(@RequestParam String content)
    {


        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        JSONObject json = new JSONObject();
        json.put("loginToken", content);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Authorization","Basic "+ Base64.getUrlEncoder()
                .encodeToString(("b895ee620f3ca3cf4f45aedb"+ ":" + "b215c14a1a06814ef264d5af").getBytes()));
        //将请求头部和参数合成一个请求
        HttpEntity<String> requestEntity = new HttpEntity<>(json.toString(), headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<String> response = client.postForEntity("https://api.verification.jpush.cn/v1/web/loginTokenVerify", requestEntity, String.class);
        System.out.println(response.getBody());
//
        JSONObject jsonObject = JSON.parseObject(response.getBody());
        if (jsonObject.getIntValue("code") != 8000){
            return AjaxResult.error("没有获取到手机号码");
        }

        String phone = "";

        try {
            phone = RSADecrypt.decrypt(jsonObject.getString("phone"),
                    "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAK9ahutIXhGwY+6U" +
                            "O4hFC31xwaCZuGnIozgcGjN9cCN6FxF7Exos+QDy9+N/J/uo7zmoBLO7uVlPUjrF" +
                            "DcYnXTfEzBasBi3/uAqH2dpwWBrNB2GZ5AbMrJYqs62z0fwlQBcEUFIbWLpRTKOv" +
                            "IeGXX6l6JnyixoujH0Y4JhABrVCnAgMBAAECgYAke34kh2ri3UL9SSPVpx/L2pYB" +
                            "VtoSUCb9LoOZANkK2ITiIywHPyITO3mtgDAOYMhcw4Mu7biTRziBd6v09Q2ki3Xy" +
                            "tao5itu688gIBuEi3W5eIzuWFMsYu5Cm+kihAqD7UzQl2AdwQ78Oocx69gFLIwrR" +
                            "6BGgf/n1fvdVxew5KQJBANyvNZ2RXZvJq3CAx0IEbmcYWgY8XxGGndcY6yRdyANb" +
                            "d6YXl7jG+8Z1sc17ZjSUsw6LIYw3TDmA0dizi/Bnwz0CQQDLaj+ibMsJsT4v+zij" +
                            "oZ03l5Uv2d98ffp0XCwKa4/AJkLz9rt4flNB34Scx95qgTEuMab/lmPwFBKJYCPN" +
                            "V9GzAkAvzXQbsYVJXaHZOMvwrO0NP+UgPKuLLFG8ahVlRzswHvwH6kxfJhsbnhrp" +
                            "m7VD5oHywIh/yuqj+hd6jUnexVsxAkAPK+WDH8ok9utEeOBIlA090Dh4US+yAVNk" +
                            "ylsei9c05aWovIZO/l0HVLx3VRDpsKkSYPGrrnPVvCmFxX3mGt6xAkBG6GJ5YgVS" +
                            "c7YZ+I6g08gqCa4R2EoCqJn/Mf3X3/mZXLNtViRUY4DeAKYELrPGrMKNvU3fCUgv" +
                            "WQVbCThhT3st");
        }catch (Exception e){

        }

        if (StringUtils.isEmpty(phone) || phone.length()!=11){
            return AjaxResult.error("没有获取到手机号");
        }

        JiajiaUser user = new JiajiaUser();
        user.setPhone(phone);
        List<JiajiaUser> userList =  userService.selectJiajiaUserList(user);
        if (userList.isEmpty()){
            user.setName("百吉星社工用户");
            userService.insertJiajiaUser(user);
        }else {
            user = userList.get(0);
        }
        if (user.getDel().intValue() == 1)return AjaxResult.error("此账户已注销!");
        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(TokenUtil.jiajia_reids_token+uuid,user.getId()+"",60, TimeUnit.DAYS);
        return AjaxResult.success(uuid);
    }


    @ApiOperation("获取短信验证码")
    @PostMapping("getLoginCode")
    public AjaxResult getLoginCode(@RequestParam String phone){

        try {
            String code = ""+(int)((Math.random()*9+1)*1000);

            //开始发送短信
            SendSmsResponse response = SendSms.sendSms(phone,code, SmsTemplete.TP_LOGIN_CODE);
            if (response.getCode().equals("OK")){
                //存redis
                redisTemplate.opsForValue().set( TokenUtil.jiajia_user_phone_login_code + phone,code,SmsTemplete.CODE_EXPIRED, TimeUnit.MINUTES);
                return AjaxResult.success("短信发送成功");
            }else{
                return AjaxResult.error("发送失败"+response.getMessage());
            }

        }catch (Exception e){
            System.out.println(e.toString());
            return AjaxResult.error("发送异常"+e.toString());
        }

    }


    @ApiOperation("个人信息")
    @PostMapping("/info")
    public AjaxResult info() {
        try {
            JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
            List<JiajiaProxyApplication> proxyApplications= proxyApplicationService.selectByUserId(user.getId());
            user.getParams().put("proxy",proxyApplications);
            if (user == null)return AjaxResult.notLogin();
            //查询活动
            JiajiaHuoDong huoDong = new JiajiaHuoDong();
            huoDong.setType(2l);
            huoDong.setIsShow(1l);
            huoDong.setDel(0l);
            List<JiajiaHuoDong> huoDongList = huoDongService.selectJiajiaHuoDongList(huoDong);

            user.getParams().put("huoDongUrl","");
            if (!huoDongList.isEmpty()){
                user.getParams().put("huoDongUrl",huoDongList.get(0));
            }
            user.getParams().put("isRead",0);//0不展示小红点 1展示
            //查询是否有未读消息
            long count = PageHelper.count(new ISelect() {
                @Override
                public void doSelect() {
                    JiajiaMessage message = new JiajiaMessage();
                    message.setUid(user.getId());
                    message.setType(2);
                    message.setIslook(0);
                    messageService.selectJiajiaMessageList(message);
                }
            });
            if (count > 0){
                user.getParams().put("isRead",1);//0不展示小红点 1展示
            }

            return AjaxResult.success(user);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }


    @ApiOperation("修改个人信息")
    @PostMapping("/updateUser")
    public AjaxResult updateUser(@RequestParam(required = false) @ApiParam(value = "姓名") String name,
                                 @RequestParam(required = false) @ApiParam(value = "头像路径") String avatar,
                                 @RequestParam(required = false) @ApiParam(value = "性别 1男 2女") Integer sex)
    {
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user==null)return AjaxResult.refreshAgain();

        user.setName(name);
        user.setAvatar(avatar);
        user.setSex(sex);
        userService.updateJiajiaUser(user);

        return AjaxResult.success("修改成功");
    }

    @ApiOperation("注销账户")
    @PostMapping("/zhuXiao")
    public AjaxResult zhuXiao(){

//        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
//        user.setDel(1);
//        userService.updateJiajiaUser(user);

        return AjaxResult.success();
    }

    @ApiOperation("用户报名社工")
    @GetMapping("/enroll")
    public AjaxResult enroll(){
        AjaxResult ajaxResult =userService.enroll();
        return ajaxResult;
    }

    @ApiOperation("邀请用户列表")
    @GetMapping("/inviteUserList")
    public AjaxResult inviteUserList(){
        AjaxResult ajaxResult =userService.inviteUserList();
        return AjaxResult.success(ajaxResult);
    }

    @ApiOperation("我的邀请代理")
    @GetMapping("/inviteAgentList")
    public AjaxResult inviteAgentList(Integer type){
        AjaxResult ajaxResult =userService.inviteAgentList(type);
        return AjaxResult.success(ajaxResult);
    }

    @ApiOperation("邀请用户列表")
    @GetMapping("/inviteWorkerList")
    public AjaxResult inviteWorkerList(){
        AjaxResult ajaxResult =userService.inviteWorkerList();
        return AjaxResult.success(ajaxResult);
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        List<JiajiaUser> jiajiaUsers = userService.selectJiajiaUserList(new JiajiaUser());
        return AjaxResult.success(jiajiaUsers);
    }


    @GetMapping("/myWallet")
    public AjaxResult myWallet() {
        Long uid = TokenUtil.getUid();
        JiajiaUser jiajiaUser = userService.selectJiajiaUserById(uid);
        BigDecimal money =  jiajiaUser.getMoney() ==null ? BigDecimal.ZERO :  jiajiaUser.getMoney();

        return AjaxResult.success(money.divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN));
    }




}
